// miniprogram/pages/proxy_return/proxy_return.js
const db = require('../../utils/db');
const strutil = require('../../utils/str');
const datetime = require('../../utils/datetime')

let recordId;

Page({
  data: {
    record: {
      type: Object,
      value: {}
    },
    records: {
      type: Array,
      value: []
    },
    isDetailPage: {
      type: Boolean,
      value: false
    },
    record: {
      type: Object,
      value: {}
    },
    isReturning: {
      type: Boolean,
      value: false
    },
    busy: {
      type: Boolean,
      value: false
    },
    found: {
      type: Boolean,
      value: false
    },
    late: {
      type: Boolean,
      value: false
    },
    submitting: {
      type: Boolean,
      value: false
    }
  },

  onLoad: function (options) {
    recordId = options.recordId;
  },

  onReady: function () {
    this.setData({
      submitting: false
    });
    if (recordId) {
      this.setData({
        isDetailPage: true,
        busy: true,
        found: true
      });
      db.getRecord(recordId).then(record => {
        console.log(record);
        const isLate = Date.now() > record['expectedReturnTime'];
        record['borrowTime'] = datetime.toFriendlyTime(record['borrowTime']);
        record['expectedReturnTime'] = datetime.toFriendlyTime(record['expectedReturnTime']);
        this.setData({
          busy: false,
          found: record != null,
          record: record,
          late: isLate
        });
      });
    } else {
      this.setData({
        isDetailPage: false
      });
    }
  },

  onShow: function () {

  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onReturnTap: function () {
    this.setData({
      submitting: true
    });
    db.makeReturnDelivery(this.data.record._id).then(() => {
      this.setData({
        submitting: false
      });
      wx.showToast({
        title: '已预约取书归还',
      });
      wx.navigateBack();
    });
  }
})